package cn.gok.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

/**
    测试文件下载
 */
@Controller
public class FileDownloadController {


    @RequestMapping("/toDownlaodPage.do")
    public String toDownlaodPage(HttpSession session, ModelMap modelMap){
        modelMap.addAttribute("fileName0",session.getAttribute("fileName0"));
        modelMap.addAttribute("fileName1",session.getAttribute("fileName1"));
        return "download";
    }



    /**
            整个文件下载过程，即是返回ResponseEntity 对象的过程 ，其构造器如下：
                        ResponseEntity(T body, MultiValueMap<String, String> headers,  HttpStatus status)

                 body： 一般为存放了下载数据的字节数组
                 headers： 请求头信息， MultiValueMap为接口，一般我们使用其子实现类 HttpHeaders
                 status： 响应状态码
     */
    @RequestMapping("/fileDownload.do")
    public ResponseEntity fileDownload(HttpServletRequest request, String fileName) throws IOException {

        //1、先将本地的文件读取到当前程序中
        //1.1、创建输入流
        String imagePath = request.getServletContext().getRealPath("") + "static/images";
        FileInputStream inputStream = new FileInputStream(imagePath + "/" + fileName);

        /*
            1.2、创建字节数组存放 读取到的数据
                inputStream.available()返回读到的数据字节长度

         */
        byte[] bytes = new byte[inputStream.available()];

        //1.3、将数据读到字节数组中
        inputStream.read(bytes);


        /*
            2、构建 MultiValueMap<String, String> headers 对象
                    使用其具体实现类 HttpHeaders
         */
        HttpHeaders httpHeaders = new HttpHeaders();
        //设置响应方式，以二进制流传输
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        // 告诉浏览器执行下载的操作，“attachment”告诉了浏览器进行下载,下载的文件文件名为 fileName
        httpHeaders.setContentDispositionFormData("attachment", fileName);

        //3、构建ResponseEntity 对象返回
        return new ResponseEntity(bytes,httpHeaders, HttpStatus.OK);
    }
}
